#region Code by Robert McLaws

//Last Updated: Robert McLaws
//Date: 22 Sept 2007

#endregion

#region  Import Declarations

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Xml;
using CommunityServer.Components;
using CommunityServer.Configuration;
using Telligent.Tasks;

#endregion

namespace CommunityServerStuff.Jobs
{

    /// <summary>
    /// Automatically deletes posts from the Recycle Bin after the period specified in the job.
    /// </summary>
    public class RecycleBinJob : ITask
    {

        #region Private Members

        private int _daysToRetain = 7;

        #endregion

        #region Methods

        #region Constructor

        public RecycleBinJob()
        {
        }

        #endregion

        #region Execute

        public void Execute(System.Xml.XmlNode node)
        {
            try
            {
                XmlAttribute retainNode = node.Attributes["daysToRetain"];

                if (retainNode != null)
                {
                    try { _daysToRetain = int.Parse(retainNode.Value); }
                    catch { _daysToRetain = 7; }
                }

                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString))
                {
                    string commandText = "DELETE FROM cs_posts_deleted_archive WHERE DeletedDate < @EarlierThan";
                    using (SqlCommand command = new SqlCommand(commandText, connection))
                    {
                        command.CommandType = CommandType.Text;
                        command.Parameters.AddWithValue("@EarlierThan", DateTime.Now.Subtract(new TimeSpan(_daysToRetain, 0, 0)));
                        connection.Open();
                        command.ExecuteNonQuery();
                    }
                }

            }
            catch (Exception e)
            {
                CSException csEx = new CSException(CSExceptionType.UnknownError, "The job RobertMcLaws.CommunityServerStuff.Jobs.RecycleBinJob failed." + Environment.NewLine + e.Message, (e.InnerException != null ? e.InnerException : e));
                csEx.Log();
            }

        }

        #endregion

        #endregion

    }
}